<?php
/**
  * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说 图/谱/源/码/分/享
 */
defined("IN_IA")or exit("Access denied");
global $_GPC,$_W;
$uniacid=$_GPC['uniacid'];
$op=$_GPC['op'] ? $_GPC['op'] :"index";
$uid=$_GPC['uid'];

//商城首页
if($op=='index'){
	$request=array();
    //轮播图
	$slideData=pdo_getall('cqkundian_farm_slide',array('uniacid'=>$uniacid,'status'=>1,'slide_type'=>2),'','','rank asc');
	$request['slideData']=$slideData;
    //分类
    $typeData=pdo_getall('cqkundian_farm_goods_type',array('status'=>1,'uniacid'=>$uniacid),'','','rank asc');
    $request['typeData']=$typeData;

    //推荐商品信息
    $recommendData=pdo_getall('cqkundian_farm_goods',array('is_put_away'=>1,'is_recommend'=>1,'uniacid'=>$uniacid),'','','rank asc');
    $request['recommendData']=$recommendData;

    $aboutData=pdo_get("cqkundian_farm_about",array('uniacid'=>$uniacid));
	echo json_encode($request);die;
}

if($op=='getNewGoods'){
    $request=array();
    if (empty($_GPC['page'])) {
        $page = 1;
    } else {
        $page = $_GPC['page'];
    }
    $classify=$_GPC['classify'];
    if($classify==1){
        $recommendData=pdo_getall('cqkundian_farm_goods',array('is_put_away'=>1,'is_recommend'=>1,'uniacid'=>$uniacid),'','','rank asc',array($page,16));
        $request['recommendData']=$recommendData;
    }else {
        $newGoodsData = pdo_getall('cqkundian_farm_goods', array('is_put_away' => 1, 'uniacid' => $uniacid), '', '', 'id desc', array($page, 16));
        $request['newGoodsData']=$newGoodsData;
    }
    echo json_encode($request);
}

//获取商品详细信息
if($op=='getGoodsDetail'){
	$request=array();
	$goodsid=$_GPC['goodsid'];
	$goodsData=pdo_get('cqkundian_farm_goods',array('id'=>$goodsid,'uniacid'=>$uniacid));
	$goodsData['goods_slide']=unserialize($goodsData['goods_slide']);
	$goodsData['send_goods_desc']=unserialize($goodsData['send_goods_desc']);
	$goodsData['price']=number_format($goodsData['price'],2);

	//获取商品规格信息
	$specItem=pdo_getall('cqkundian_farm_spec',array('goods_id'=>$goodsid,'uniacid'=>$uniacid));

//	//获取规格值信息
	for ($i=0; $i < count($specItem); $i++) {
		$specVal=pdo_getall('cqkundian_farm_spec_value',array('uniacid'=>$uniacid,'spec_id'=>$specItem[$i]['id']));
		$specItem[$i]['select_spec']=0;  //未选择
		for ($j=0; $j <count($specVal) ; $j++) {
			$specVal[$j]['select_val']=0;	
		}
		$specItem[$i]['specVal']=$specVal;
	}
	$request['specItem']=$specItem;

    //关于我们
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $request['aboutData']=$aboutData;
    if($goodsData['trace_id']) {
        //查询产品溯源信息
        $traceData = pdo_getall('cqkundian_farm_goods_trace', array('uniacid' => $uniacid, 'trace_id' => $goodsData['trace_id']),'','','rank asc');
        for ($i = 0; $i < count($traceData); $i++) {
            $traceData[$i]['trace_time'] = date("Y-m-d", $traceData[$i]['trace_time']);
            $traceData[$i]['img'] = unserialize($traceData[$i]['img']);
            $traceData[$i]['trace_desc'] = explode("\n", $traceData[$i]['trace_desc']);
        }
        $request['traceData'] = $traceData;

        //查询肥料使用表
        $fumierData=pdo_getall('cqkundian_farm_goods_fumier',array('uniacid'=>$uniacid,'trace_id'=>$goodsData['trace_id']),'','','use_time asc');
        if($fumierData) {
            for ($i = 0; $i < count($fumierData); $i++) {
                $fumierData[$i]['use_time'] = date("Y-m-d", $fumierData[$i]['use_time']);
            }
            $goodsData['fumierData'] = $fumierData;
        }
        //查询农药使用表
        $insecData=pdo_getall('cqkundian_farm_goods_insec',array('uniacid'=>$uniacid,'trace_id'=>$goodsData['trace_id']),'','','use_time asc');
        if($insecData) {
            for ($i = 0; $i < count($insecData); $i++) {
                $insecData[$i]['use_time'] = date("Y-m-d", $insecData[$i]['use_time']);
            }
            $goodsData['insecData'] = $insecData;
        }
    }
    $request['goodsData']=$goodsData;
	echo json_encode($request);die;
}

//动态获取规格值
if($op=='getSpec'){
	$request=array();
	$spec_id=explode(',', $_GPC['spec_id']);
	$goods_id=$_GPC['goodsid'];
	sort($spec_id);
	$sku_name=implode(',',$spec_id);
	$specVal=pdo_get('cqkundian_farm_goods_spec',array('sku_name'=>$sku_name,'goods_id'=>$goods_id));
    if(!empty($specVal)) {
        $specVal['price'] = number_format($specVal['price'], 2);
    }
	$specItem=pdo_getall('cqkundian_farm_spec_value',array('id in'=>$spec_id));
	$sku_name_arr=array();
    for($i=0;$i<count($specItem);$i++){
        $sku_name_arr[]=$specItem[$i]['spec_value'];
    }
    $sku_name_str=implode('+',$sku_name_arr);
    $request['sku_name_str']=$sku_name_str;
	$request['specVal']=$specVal;
	echo json_encode($request);die;
}

//确认下单获取商品信息和规格
if($op=='getSureGoods'){
	$request=array();
	$goods_id=$_GPC['goods_id'];
	$count=$_GPC['count'];		//购买数量
	$totalPrice=0;	//总价
	$goodsData=pdo_get('cqkundian_farm_goods',array('id'=>$goods_id,'uniacid'=>$uniacid));
	if($goodsData['is_open_sku']==1){  //存在规格值
		$spec_id=$_GPC['spec_id'];
		//规格选项
        if($spec_id) {
            $specItem = pdo_getall('cqkundian_farm_spec', array('goods_id' => $goods_id, 'uniacid' => $uniacid));
            $specVal = pdo_get('cqkundian_farm_goods_spec', array('goods_id' => $goods_id, 'id' => $spec_id, 'uniacid' => $uniacid));
            $totalPrice += $specVal['price'] * $count;
            $request['specVal'] = $specVal;

            //获取购买的sku名称
            $spec_id_arr = explode(',', $specVal['sku_name']);
            for ($i = 0; $i < count($spec_id_arr); $i++) {
                $spec_val = pdo_get('cqkundian_farm_spec_value', array('id' => $spec_id_arr[$i], 'uniacid' => $uniacid));
                for ($j = 0; $j < count($specItem); $j++) {
                    if ($specItem[$j]['id'] == $spec_val['spec_id']) {
                        $specItem[$i]['spec_val'] = $spec_val['spec_value'];
                    }
                }
            }
            $request['specItem'] = $specItem;
        }else{
            $totalPrice=$goodsData['price']*$count;
        }
	}else{
		$totalPrice+=$goodsData['price'] * $count;
	}
	$request['goodsData']=$goodsData;

    //查看用户是否有优惠券
    $couponCount=0;
    $arr=array();
    $userCoupon=pdo_getall('cqkundian_farm_user_coupon',array('uniacid'=>$uniacid,'uid'=>$uid,'status'=>0));
    if(!empty($userCoupon)) {
        for ($i = 0; $i < count($userCoupon); $i++) {
            $coupon = pdo_get('cqkundian_farm_shop_coupon', array('uniacid' => $uniacid, 'id' => $userCoupon[$i]['cid'], 'type' => 1));
            //优惠券是否过期
            if ($coupon['expiry_date'] == 1) {
                if (($userCoupon[$i]['create_time'] + ($coupon['expiry_day'] * 86400)) > time()) {
                    if ($coupon['low_cash_price'] < $totalPrice) {  //判断订单金额是否大于优惠消费最低金额
                        $couponCount += 1;
                        $arr[]=$userCoupon[$i];
                    }
                }
            } else {
                if (time() > $coupon['begin_time'] && time() < $coupon['end_time']) {
                    if ($coupon['low_cash_price'] < $totalPrice) {  //判断订单金额是否大于优惠消费最低金额
                        $couponCount += 1;
                        $arr[]=$userCoupon[$i];
                    }
                }
            }
        }
    }
    //计算运费
	$aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
	$totalPrice+=$goodsData['send_price'];	//计算总价
	$request['totalPrice']=$totalPrice;
	$request['send_price']=$goodsData['send_price'];
	$request['aboutData']=$aboutData;
	$request['couponCount']=$couponCount;
	$request['arr']=$arr;
	echo json_encode($request);die;
}

//获取商品信息列表
if($op=='getGoodsList'){
	$request=array();
	if(!empty($_GPC['page'])){
		$page=intval($_GPC['page'])+1;
	}else{
		$page=1;
	}
	if(!empty($_GPC['rank'])){
		$rank=$_GPC['rank'];
		$rank_type=$_GPC['rank_type'];
		if($rank==1){
			$order='rank '.$rank_type;
		}elseif($rank==2){
			$order='sale_count '.$rank_type;
		}else{
			$order='price '.$rank_type;
		}
	}else{
		$order='rank asc';
	}
	$condition=array();
    if(!empty($_GPC['type_id'])){
        $condition['type_id']=$_GPC['type_id'];
    }
    if(!empty($_GPC['goods_name'])){
        $condition['goods_name LIKE']='%'.$_GPC['goods_name'].'%';
    }
    $condition['uniacid']=$uniacid;
    $condition['is_put_away']=1;
	$goodsData=pdo_getall('cqkundian_farm_goods',$condition,'','',$order,array($page,12));
	$request['goodsData']=$goodsData;
	echo json_encode($request);die;
}


//生成订单
if($op=='addOrder'){
	$is_buy_type=$_GPC['is_buy_type'];
	$name=$_GPC['name'];
	$address=$_GPC['address'];
	$phone=$_GPC['phone'];
	$remark=$_GPC['remark'];
    $coupon_id=$_GPC['coupon_id'];
    $coupon_price=$_GPC['coupon_price'];
	$aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    //配置信息
    include 'function.inc.php';
    $farmSetData=getFarmSetData(array('is_open_distribution','distribution_one_price','distribution_two_price'),array('uniacid'=>$uniacid));
	if($is_buy_type==1){ 		//直接购买
		$goods_id=$_GPC['goods_id'];
		$spec_id=$_GPC['spec_id'];
		$count=$_GPC['count'];
        $goodsData=pdo_get('cqkundian_farm_goods',array('id'=>$goods_id,'uniacid'=>$uniacid));
		$insertData=array(
			'order_number'=>time().rand(100,999),
			'uid'=>$uid,
			'status'=>0,
			'create_time'=>time(),
			'name'=>$name,
			'address'=>$address,
			'phone'=>$phone,
			'uniacid'=>$uniacid,
			'remark'=>$remark,
			'send_price'=>$goodsData['send_price'],
            'coupon_id'=>$coupon_id,
            'coupon_price'=>$coupon_price,
		);

        $insertData['body']='购买'.$goodsData['goods_name'].'等商品';
		if($goodsData['is_open_sku']==1){
			$specVal=pdo_get('cqkundian_farm_goods_spec',array('goods_id'=>$goods_id,'id'=>$spec_id,'uniacid'=>$uniacid));
			$insertData['total_price']=$specVal['price']*$count;
			$insertData['total_price']+=$goodsData['send_price'];
            if($coupon_id && $coupon_price){
                $insertData['total_price']=$insertData['total_price']-$coupon_price;  //优惠券抵用
            }

            //是否开启分销
            if($farmSetData['is_open_distribution']==1){
                $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
                //当前下单用户的一级分销商
                if($user['one_distributor']!=0) {
                    $insertData['is_price']=1;
                    $one_sale = pdo_get('cqkundian_farm_user', array('uniacid' => $uniacid, 'uid' => $user['one_distributor']));
                    $insertData['one_price']=round($insertData['total_price']*($farmSetData['distribution_one_price']/100),2);
                    if($one_sale['one_distributor']!=0){
                        $insertData['two_price']=round($insertData['total_price']*($farmSetData['distribution_two_price']/100),2);
                    }
                }
            }

            $order_res=pdo_insert('cqkundian_farm_shop_order',$insertData);
			$order_id=pdo_insertid();

			//商品详情
			$insertDetail=array(
				'goods_id'=>$goods_id,
				'order_id'=>$order_id,
				'goods_name'=>$goodsData['goods_name'],
				'price'=>$specVal['price'],
				'count'=>$count,
				'spec_id'=>$spec_id,
				'uniacid'=>$uniacid,
			);
			if($specVal['spec_src']){
				$insertDetail['cover']=$specVal['spec_src'];
			}else{
				$insertDetail['cover']=$goodsData['cover'];
			}
		}else{		//没有规格

            $insertData['total_price']=$goodsData['price']*$count;
            $insertData['total_price']+=$goodsData['send_price'];

            //是否开启分销
            if($farmSetData['is_open_distribution']==1){
                $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
                //当前下单用户的一级分销商
                if($user['one_distributor']!=0) {
                    $insertData['is_price']=1;
                    $one_sale = pdo_get('cqkundian_farm_user', array('uniacid' => $uniacid, 'uid' => $user['one_distributor']));
                    $insertData['one_price']=round($insertData['total_price']*($farmSetData['distribution_one_price']/100),2);
                    if($one_sale['one_distributor']!=0){
                        $insertData['two_price']=round($insertData['total_price']*($farmSetData['distribution_two_price']/100),2);
                    }
                }
            }

            $order_res=pdo_insert('cqkundian_farm_shop_order',$insertData);
            $order_id=pdo_insertid();
			//商品详情
			$insertDetail=array(
				'goods_id'=>$goods_id,
				'order_id'=>$order_id,
				'goods_name'=>$goodsData['goods_name'],
				'price'=>$goodsData['price'],
				'count'=>$count,
				'spec_id'=>$spec_id,
				'uniacid'=>$uniacid,
				'cover'=>$goodsData['cover'],
			);
		}
		$detail_res=pdo_insert('cqkundian_farm_shop_order_detail',$insertDetail);
		if($order_res && $detail_res){
            if($coupon_id && $coupon_price){
                //修改优惠券使用
                pdo_update('cqkundian_farm_user_coupon',array('status'=>1),array('uniacid'=>$uniacid,'uid'=>$uid,'cid'=>$coupon_id));
            }
			echo json_encode(array('code'=>1,'order_id'=>$order_id));die;
		}else{
			echo json_encode(array('code'=>2));die;
		}
	}elseif($is_buy_type==2){  //从购物车中购买
		$cart_id_str=$_GPC['cart_id'];
		$cart_id=explode('_',$cart_id_str);
		$insertData=array(
			'order_number'=>time().rand(100,999),
			'uid'=>$uid,
			'status'=>0,
			'create_time'=>time(),
			'name'=>$name,
			'address'=>$address,
			'phone'=>$phone,
			'uniacid'=>$uniacid,
			'remark'=>$remark,'coupon_id'=>$coupon_id,
            'coupon_price'=>$coupon_price,
		);
		$cartData=pdo_getall('cqkundian_farm_cart',array('id in'=>$cart_id,'uniacid'=>$uniacid));
        $newGoodsData=array();
        for($j=0;$j<count($cartData);$j++){
            $newGoodsData[]=pdo_get('cqkundian_farm_goods',array('uniacid'=>$uniacid,'id'=>$cartData[$j]['goods_id']));
        }
        $send_price=0;
        for ($m=0;$m<count($newGoodsData);$m++){
            $send_price+=$newGoodsData[$m]['send_price'];
        }
        $insertData['send_price']=$send_price;
		$totalPrice=0;
		for($i=0;$i<count($cartData);$i++){
			$totalPrice+=$cartData[$i]['price']*$cartData[$i]['count'];
		}
        $insertData['body']='购买'.$cartData[0]['goods_name'].'等商品';
		$insertData['total_price']=$totalPrice+$send_price;
        if($coupon_id && $coupon_price){
            $insertData['total_price']=$insertData['total_price']-$coupon_price;
        }

        //是否开启分销
        if($farmSetData['is_open_distribution']==1){
            $user=pdo_get('cqkundian_farm_user',array('uniacid'=>$uniacid,'uid'=>$uid));
            //当前下单用户的一级分销商
            if($user['one_distributor']!=0) {
                $insertData['is_price']=1;
                $one_sale = pdo_get('cqkundian_farm_user', array('uniacid' => $uniacid, 'uid' => $user['one_distributor']));
                $insertData['one_price']=round($insertData['total_price']*($farmSetData['distribution_one_price']/100),2);
                if($one_sale['one_distributor']!=0){
                    $insertData['two_price']=round($insertData['total_price']*($farmSetData['distribution_two_price']/100),2);
                }
            }
        }

		$order_res=pdo_insert('cqkundian_farm_shop_order',$insertData);
		$order_id=pdo_insertid();
		$detail_res=0;
		for($i=0;$i<count($cartData);$i++){
			$insertDetail=array(
				'goods_id'=>$cartData[$i]['goods_id'],
				'order_id'=>$order_id,
				'goods_name'=>$cartData[$i]['goods_name'],
				'price'=>$cartData[$i]['price'],
				'count'=>$cartData[$i]['count'],
				'spec_id'=>$cartData[$i]['spec_id'],
				'uniacid'=>$uniacid,
                'cover'=>$cartData[$i]['cover'],
			);
			$detail_res+=pdo_insert('cqkundian_farm_shop_order_detail',$insertDetail);
		}
		if($order_res && $detail_res){
            if($coupon_id && $coupon_price){
                //修改优惠券使用
                pdo_update('cqkundian_farm_user_coupon',array('status'=>1),array('uniacid'=>$uniacid,'uid'=>$uid,'cid'=>$coupon_id));
            }
            pdo_delete('cqkundian_farm_cart',array('id in'=>$cart_id,'uniacid'=>$uniacid,'uid'=>$uid));
		    echo json_encode(array('code'=>1,'order_id'=>$order_id));die;
		}else{
			echo json_encode(array('code'=>2));die;
		}
	}
}

//支付回调地址
if($op=='notify'){

	$order_id=$_GPC['order_id'];
    $prepay_id_str=$_GPC['prepay_id'];
	$orderData=pdo_get('cqkundian_farm_shop_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    if($orderData['status']==1) {
        include 'function.inc.php';
        //更新商品的销量库存
        updateSaleCount($order_id, $uniacid);
        updateGoodsCount($order_id, $uniacid);
        //更新积分记录
        insertIntegral($uniacid, $order_id);
        //向用户推送消息
        $prepay_id = explode('=', $prepay_id_str);
        $wxData = pdo_get('cqkundian_farm_wx_set', array('uniacid' => $uniacid));
        //给用户发送模板消息
        $page = '/kundian_farm/pages/shop/orderList/index';
        $res_user_send = send_msg_to_user($orderData, $prepay_id[1], $_W['openid'], $uniacid, $page);
        //给店家推送消息
        $wx_openid = unserialize($wxData['get_openid']);
        for ($i = 0; $i < count($wx_openid); $i++) {
            $res_send_shop = send_template_message($wx_openid[$i], $orderData, $uniacid);
        }
        echo json_encode(array('code' => 1));
        die;
    } else {
        echo json_encode(array('code' => 2));
        die;
    }
}

/**
 * 更新商品销量
 * @param  [type] $order_id [description]
 * @param  [type] $uniacid  [description]
 * @return [type]           [description]
 */
function updateSaleCount($order_id,$uniacid){
	$orderDetail=pdo_getall('cqkundian_farm_shop_order_detail',array('order_id'=>$order_id,'uniacid'=>$uniacid));
	for($i=0;$i<count($orderDetail);$i++){
		$goods_where=array(
			'id'=>$orderDetail[$i]['goods_id'],
			'uniacid'=>$uniacid,
		);
		pdo_update('cqkundian_farm_goods',array('sale_count +='=>$orderDetail[$i]['count']),$goods_where);
	}
}

/**
 * 更新商品库存
 * @param $orderid
 * @param $uniacid
 */
function updateGoodsCount($orderid,$uniacid){
    $orderDetail=pdo_get('cqkundian_farm_shop_order_detail',array('order_id'=>$orderid,'uniacid'=>$uniacid));
    if($orderDetail['spec_id']!=0){
        pdo_update('cqkundian_farm_goods_spec',array('count -='=>$orderDetail['count']),array('id'=>$orderDetail['spec_id'],'uniacid'=>$uniacid));
    }else{
        pdo_update('cqkundian_farm_goods',array('count -='=>$orderDetail['count']),array('id'=>$orderDetail['goods_id'],'uniacid'=>$uniacid));
    }
}


/**
 * 添加积分记录
 * @param $uniacid
 * @param $uid
 * @param $score
 */
function insertIntegral($uniacid,$order_id){
    $orderData=pdo_get('cqkundian_farm_shop_order',array('id'=>$order_id,'uniacid'=>$uniacid));
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    $userData=pdo_get('cqkundian_farm_user',array('uid'=>$orderData['uid'],'uniacid'=>$uniacid));
    $score=round($orderData['total_price']/$aboutData['pay_integral']);
    pdo_update('cqkundian_farm_user',array('score +='=>$score),array('uid'=>$orderData['uid'],'uniacid'=>$uniacid));
    $insertData=array(
        'uid'=>$orderData['uid'],
        'uniacid'=>$uniacid,
        'create_time'=>time(),
        'score_type'=>1,
        'score'=>$score,
        'body'=>$orderData['body']?$orderData['body']:"购物",
        'now_score'=>$userData['score']+$score,
    );
    pdo_insert('cqkundian_farm_integral_record',$insertData);
}



